package org.goodsmanager.controller;

import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.common.Result;
import org.goodsmanager.entity.Cart;
import org.goodsmanager.service.CartService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车控制器
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Controller
@RequestMapping("/shop/cart")
@RequiredArgsConstructor
public class CartController {

    private final CartService cartService;

    /**
     * 获取当前用户ID（从session中获取）
     */
    private String getCurrentUserId(HttpSession session) {
        // 实际项目中应该从session中获取用户ID
        // 这里暂时使用固定值作为示例
        String userId = (String) session.getAttribute("userId");
        if (userId == null) {
            // 如果用户未登录，可以使用临时用户ID或session ID
            userId = session.getId();
            session.setAttribute("userId", userId);
        }
        return userId;
    }

    /**
     * 购物车页面
     */
    @GetMapping({"", "/"})
    public String cartPage(HttpSession session, Model model) {
        try {
            String userId = getCurrentUserId(session);
            
            // 获取购物车列表
            List<Cart> cartItems = cartService.getCartByUserId(userId);
            
            // 获取购物车统计信息
            Map<String, Object> statistics = cartService.getCartStatistics(userId);
            
            model.addAttribute("cartItems", cartItems);
            model.addAttribute("statistics", statistics);
            
            return "shop/cart";
        } catch (Exception e) {
            log.error("加载购物车页面失败", e);
            model.addAttribute("error", "加载购物车页面失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    @ResponseBody
    public Result addToCart(@RequestParam String productId,
                           @RequestParam(defaultValue = "1") Integer quantity,
                           HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            Cart cartItem = cartService.addToCart(userId, productId, quantity);
            
            Map<String, Object> data = new HashMap<>();
            data.put("cartItem", cartItem);
            data.put("cartItemCount", cartService.getCartItemCount(userId));
            
            return Result.success("商品已添加到购物车", data);
        } catch (Exception e) {
            log.error("添加商品到购物车失败", e);
            return Result.error("添加商品到购物车失败: " + e.getMessage());
        }
    }

    /**
     * 更新购物车项数量
     */
    @PostMapping("/update")
    @ResponseBody
    public Result updateQuantity(@RequestParam String productId,
                               @RequestParam Integer quantity,
                               HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            cartService.updateQuantity(userId, productId, quantity);
            
            // 返回更新后的购物车统计信息
            Map<String, Object> statistics = cartService.getCartStatistics(userId);
            
            return Result.success("数量已更新", statistics);
        } catch (Exception e) {
            log.error("更新购物车项数量失败", e);
            return Result.error("更新数量失败: " + e.getMessage());
        }
    }

    /**
     * 更新购物车项选中状态
     */
    @PostMapping("/select")
    @ResponseBody
    public Result updateSelected(@RequestParam String productId,
                               @RequestParam Boolean selected,
                               HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            cartService.updateSelected(userId, productId, selected);
            
            // 返回更新后的购物车统计信息
            Map<String, Object> statistics = cartService.getCartStatistics(userId);
            
            return Result.success("状态已更新", statistics);
        } catch (Exception e) {
            log.error("更新购物车项选中状态失败", e);
            return Result.error("更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 批量更新购物车项选中状态
     */
    @PostMapping("/selectBatch")
    @ResponseBody
    public Result updateSelectedBatch(@RequestParam List<String> productIds,
                                    @RequestParam Boolean selected,
                                    HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            cartService.updateSelectedBatch(userId, productIds, selected);
            
            // 返回更新后的购物车统计信息
            Map<String, Object> statistics = cartService.getCartStatistics(userId);
            
            return Result.success("状态已更新", statistics);
        } catch (Exception e) {
            log.error("批量更新购物车项选中状态失败", e);
            return Result.error("更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 全选/取消全选
     */
    @PostMapping("/selectAll")
    @ResponseBody
    public Result updateSelectedAll(@RequestParam Boolean selected,
                                   HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            cartService.updateSelectedAll(userId, selected);
            
            // 返回更新后的购物车统计信息
            Map<String, Object> statistics = cartService.getCartStatistics(userId);
            
            return Result.success("状态已更新", statistics);
        } catch (Exception e) {
            log.error("更新用户所有购物车项选中状态失败", e);
            return Result.error("更新状态失败: " + e.getMessage());
        }
    }

    /**
     * 删除购物车项
     */
    @PostMapping("/remove")
    @ResponseBody
    public Result removeFromCart(@RequestParam String productId,
                                HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            cartService.removeFromCart(userId, productId);
            
            // 返回更新后的购物车统计信息
            Map<String, Object> statistics = cartService.getCartStatistics(userId);
            
            return Result.success("商品已从购物车移除", statistics);
        } catch (Exception e) {
            log.error("删除购物车项失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除购物车项
     */
    @PostMapping("/removeBatch")
    @ResponseBody
    public Result removeFromCartBatch(@RequestParam List<String> productIds,
                                     HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            cartService.removeFromCartBatch(userId, productIds);
            
            // 返回更新后的购物车统计信息
            Map<String, Object> statistics = cartService.getCartStatistics(userId);
            
            return Result.success("商品已从购物车移除", statistics);
        } catch (Exception e) {
            log.error("批量删除购物车项失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 清空购物车
     */
    @PostMapping("/clear")
    @ResponseBody
    public Result clearCart(HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            cartService.clearCart(userId);
            
            Map<String, Object> data = new HashMap<>();
            data.put("cartItemCount", 0);
            
            return Result.success("购物车已清空", data);
        } catch (Exception e) {
            log.error("清空购物车失败", e);
            return Result.error("清空购物车失败: " + e.getMessage());
        }
    }

    /**
     * 获取购物车项数量
     */
    @GetMapping("/count")
    @ResponseBody
    public Result getCartItemCount(HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            int count = cartService.getCartItemCount(userId);
            
            Map<String, Object> data = new HashMap<>();
            data.put("cartItemCount", count);
            
            return Result.success("获取成功", data);
        } catch (Exception e) {
            log.error("获取购物车项数量失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取购物车统计信息
     */
    @GetMapping("/statistics")
    @ResponseBody
    public Result getCartStatistics(HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            Map<String, Object> statistics = cartService.getCartStatistics(userId);
            
            return Result.success("获取成功", statistics);
        } catch (Exception e) {
            log.error("获取购物车统计信息失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 获取选中的购物车项
     */
    @GetMapping("/selected")
    @ResponseBody
    public Result getSelectedCartItems(HttpSession session) {
        try {
            String userId = getCurrentUserId(session);
            List<Cart> cartItems = cartService.getSelectedCartItems(userId);
            
            Map<String, Object> data = new HashMap<>();
            data.put("cartItems", cartItems);
            
            return Result.success("获取成功", data);
        } catch (Exception e) {
            log.error("获取选中的购物车项失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }
}